﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Optimization;

namespace com.kmer.library {
	/// <summary>
	/// Bundle管理器
	/// </summary>
	public static class BundleManager {
		static BundleCollection __bundles;
		/// <summary>
		/// 获取默认的绑定集合。
		/// </summary>
		public static BundleCollection Bundles {
			get {
				return __bundles??(__bundles=BundleTable.Bundles);
			}

			set {
				__bundles = value;
			}
		}

		/// <summary>
		/// 初始化
		/// </summary>
		public static void Init() {
			BundleManager.Init(System.Web.Optimization.BundleTable.Bundles);
		}
		internal static bool IsExists(string bundlePath) {
			return BundleManager.Bundles.Count > 0 && Bundles.Any(item => item.Path == bundlePath);
		}
		internal static void Add(Bundle bundle) {
			BundleManager.Bundles.Add(bundle);
		}
		/// <summary>
		/// 初始化
		/// </summary>
		/// <param name="bundles"></param>
		public static void Init(BundleCollection bundles) {
			Bundles = bundles;
		}
		/// <summary>
		/// 定义CSS包
		/// </summary>
		/// <param name="packer">包</param>
		public static void AddStylePacker(BundlePacker packer) {
			StylesHelper.AddPacker(packer);
		}
		/// <summary>
		/// 定义JS包
		/// </summary>
		/// <param name="packer">包</param>
		public static void AddJavaScriptPacker(BundlePacker packer) {
			JavaScriptHelper.AddPacker(packer);
		}
		internal static string MakeBundleName(string type, params string[] urls) {
			var array =
				urls.SelectMany(url => url.Split('/'))
					.SelectMany(url => url.Split('.'))
					.Distinct()
					.Except(new[] { "~", type });

			return string.Join("-", array);
		}
	}//end class
	/// <summary>
	/// 包
	/// </summary>
	public class BundlePacker {
		/// <summary>
		/// 包名，唯一
		/// </summary>
		public string Name { get; set; }
		/// <summary>
		/// 包含的文件
		/// </summary>
		internal IList<string> Files { get; set; }
		/// <summary>
		/// 把资源文件包含到包里
		/// </summary>
		/// <param name="files"></param>
		/// <returns></returns>
		public BundlePacker Include(params string[] files) {
			if (this.Files == null) this.Files = new List<string>();
			foreach (var file in files) {
				this.Files.Add(file);
			}
			return this;
		}
	}//end class
}//end namespace
